<script setup lang="ts">
import { h, onMounted, watch } from 'vue'
import {
  NCard,
  NDataTable,
  NButton,
  NSelect,
  NInput,
  NSpace,
  NTag,
  NEmpty,
  NSpin,
  useMessage,
  type DataTableColumns,
} from 'naive-ui'
import { useLogger, type LogLevel } from './useLogger'
import type { LogEntry } from '../../utils/wails-api'

const message = useMessage()
const { logs, total, loading, error, levelFilter, moduleFilter, messageFilter, fetchLogs, clearLogs, refreshLogs } = useLogger()

// 日志级别选项
const levelOptions = [
  { label: '全部', value: '' },
  { label: 'Debug', value: 'debug' },
  { label: 'Info', value: 'info' },
  { label: 'Warn', value: 'warn' },
  { label: 'Error', value: 'error' },
  { label: 'Fatal', value: 'fatal' },
]

// 表格列定义
const columns: DataTableColumns<LogEntry> = [
  {
    title: '时间',
    key: 'time',
    width: 180,
    render: (row) => {
      const date = new Date(row.time)
      return date.toLocaleString('zh-CN')
    },
  },
  {
    title: '级别',
    key: 'level',
    width: 100,
    render: (row) => {
      const levelColors: Record<string, 'default' | 'info' | 'warning' | 'error' | 'success'> = {
        debug: 'default',
        info: 'info',
        warn: 'warning',
        error: 'error',
        fatal: 'error',
      }
      const tagType = levelColors[row.level] || 'default'
      return h(NTag, { type: tagType }, { default: () => row.level.toUpperCase() })
    },
  },
  {
    title: '模块',
    key: 'module',
    width: 120,
  },
  {
    title: '消息',
    key: 'message',
    ellipsis: {
      tooltip: true,
    },
  },
]

// 监听级别过滤器变化（下拉选择不会导致抖动）
watch([levelFilter], () => {
  fetchLogs()
})

// 搜索处理函数
const handleSearch = (): void => {
  fetchLogs()
}

// 输入框回车搜索
const handleInputEnter = (): void => {
  handleSearch()
}

// 清空日志
const handleClear = async (): Promise<void> => {
  try {
    await clearLogs()
    message.success('日志已清空')
  } catch (err) {
    message.error(err instanceof Error ? err.message : '清空日志失败')
  }
}

// 刷新日志
const handleRefresh = async (): Promise<void> => {
  await refreshLogs()
  message.success('日志已刷新')
}

// 初始化加载
onMounted(() => {
  fetchLogs()
})
</script>

<template>
  <n-card class="log-viewer">
    <template #header-extra>
      <n-space>
        <n-button size="small" @click="handleRefresh" :loading="loading">
          刷新
        </n-button>
        <n-button size="small" type="error" @click="handleClear" :loading="loading">
          清空
        </n-button>
      </n-space>
    </template>

    <n-space vertical :size="16">
      <!-- 过滤器 -->
      <n-space align="center">
        <n-select
          v-model:value="levelFilter"
          :options="levelOptions"
          placeholder="选择日志级别"
          style="width: 150px"
          clearable
        />
        <n-input
          v-model:value="moduleFilter"
          placeholder="输入模块名称"
          style="width: 150px"
          clearable
          @keyup.enter="handleInputEnter"
        />
        <n-input
          v-model:value="messageFilter"
          placeholder="搜索消息内容"
          style="width: 200px"
          clearable
          @keyup.enter="handleInputEnter"
        />
        <n-button type="primary" @click="handleSearch" :loading="loading">
          搜索
        </n-button>
        <div style="flex: 1" />
        <span style="color: var(--n-text-color-2); font-size: 12px; line-height: 32px">
          共 {{ total }} 条日志
        </span>
      </n-space>

      <!-- 日志表格 -->
      <n-spin :show="loading">
        <n-data-table
          :columns="columns"
          :data="logs"
          :pagination="false"
          :max-height="400"
          virtual-scroll
        >
          <template #empty>
            <n-empty description="暂无日志" />
          </template>
        </n-data-table>
      </n-spin>

      <!-- 错误提示 -->
      <div v-if="error" style="color: var(--n-error-color)">
        {{ error }}
      </div>
    </n-space>
  </n-card>
</template>

<style scoped>
.log-viewer {
  width: 100%;
}
</style>

